import React, { PureComponent } from 'react'
import { Button, Modal } from 'antd';
import FileViewer from 'react-file-viewer'
import Error from '../Error';

export default class FileViewerCpn extends PureComponent {
  constructor(props){
    super(props)
    this.state = {
      list: [
        {id: 1, file: 'http://localhost:3002/static/小程序中多商户支付调研.pdf'},
        {id: 2, file: 'http://localhost:3002/static/小程序多商户绑定.docx'},
      ],
      file: null,
      type: null,
      isModalOpen: false,
      isView: false,
    }
  }
  handleView = (file, type) => {
    this.setState({
      isModalOpen: true,
      file,
      type
    }, () => {
      this.timer = setTimeout(() => {
        this.setState({isView: true})
      }, 2000)
    })
  }
  handleOk = () => {
    this.setState({isModalOpen: false}, () => {clearTimeout(this.timer)})
  }

  handleCancel = () => {
    this.setState({isModalOpen: false}, () => {clearTimeout(this.timer)})
  }

  onError = (e) => {
    console.log(e, 'error in file-viewer');
  }
  render() {
    const {isModalOpen, isView, list, file, type} = this.state
    return (
      <div>
        {
          list.map(item => {
            const splitFile = item.file.split('/')
            const fileName = splitFile[splitFile.length - 1]
            const name = fileName.substring(0, fileName.lastIndexOf('.'))
            const type = fileName.substring(fileName.lastIndexOf('.')+1)
            return <Button key={item.id} type="primary" onClick={() => this.handleView(item.file, type)}>{name}</Button>
          })
        }
        <Modal open={isModalOpen} onOk={this.handleOk} onCancel={this.handleCancel} width={800} footer={null}>
          <div className='file_viewer_wrap'>
            {
              isView ?
                <FileViewer
                  fileType={type}
                  filePath={file}
                  errorComponent={Error}
                  onError={this.onError}/>
              : null
            }
          </div>
        </Modal> 
      </div>
    )
  }
}
